<template>
  <div @keydown.enter="handleSubmit">
    <Form ref="loginForm" :model="form" :rules="rules">
      <FormItem prop="username">
        <Input v-model.trim="form.username" placeholder="请输入用户名">
        <span slot="prepend">
          <Icon :size="16" type="person"></Icon>
        </span>
        </Input>
      </FormItem>
      <FormItem prop="password">
        <Input type="password" v-model="form.password" placeholder="请输入密码">
        <span slot="prepend">
          <Icon :size="14" type="locked"></Icon>
        </span>
        </Input>
      </FormItem>
      <FormItem>
        <Button @click="handleSubmit" type="primary" :loading="loginLoading" long>
          <span v-if="loginLoading">登录中</span>
          <span v-else>登录</span>
        </Button>
      </FormItem>
    </Form>
  </div>
</template>
<script>
  export default {
    name: 'LoginForm',
    props: {
      usernameRules: {
        type: Array,
        default: () => {
          return [
            {required: true, message: '账号不能为空', trigger: 'blur'}
          ]
        }
      },
      passwordRules: {
        type: Array,
        default: () => {
          return [
            {required: true, message: '密码不能为空', trigger: 'blur'}
          ]
        }
      }
    },
    data() {
      return {
        form: {
          username: '',
          password: ''
        },
        loginLoading: false
      }
    },
    computed: {
      rules() {
        return {
          username: this.usernameRules,
          password: this.passwordRules
        }
      }
    },
    methods: {
      handleSubmit() {
        this.$refs.loginForm.validate((valid) => {
          if (valid) {
            this.loginLoading = true;
            this.$emit('on-success-valid', {
              username: this.form.username,
              password: this.form.password
            }, () => {
              this.loginLoading = false
            })
          }
        })
      }
    }
  }
</script>
